<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MyImage {
	public function __construct() {}

	public function create_thumbnail($temp_path, $screen_dim , $scaled, $new_dim, $new_thumb_path){
		$a_func = array();
		$img_type = 0;
		if(!function_exists('exif_imagetype')){
			$CI =& get_instance();
			$CI->load->helper('file');
			$ext = get_mime_by_extension($temp_path);
			switch ($ext) {
				case 'image/jpeg': $img_type = IMAGETYPE_JPEG; break;
				case 'image/png':  $img_type = IMAGETYPE_PNG;  break;
				default: break;
			}
		} else {
			$img_type = exif_imagetype($temp_path);	
		}
		if($img_type == IMAGETYPE_JPEG){
			$a_func['imagecreate']  = 'imagecreatefromjpeg';
			$a_func['image_render'] = 'imagejpeg';
			$a_func['return_type']  = 'image/jpeg';
			$a_func['quad']         = 100;
		} elseif($img_type == IMAGETYPE_PNG){
			$a_func['imagecreate']  = 'imagecreatefrompng';
			$a_func['image_render'] = 'imagepng';
			$a_func['return_type']  = 'image/png';
			$a_func['quad']         = 9;
		} else {
			return false;
		}

		// origin image
		$im         = $a_func['imagecreate']($temp_path);
		$imsize     = getimagesize($temp_path);
		$ini_x_size = $imsize[0];
		$ini_y_size = $imsize[1];

		// zoom tile
		$z_tile = $ini_x_size / $screen_dim['width'];

		// relative point - dimension - zoom ratio
		$des_w   = intval($scaled['width']  * $z_tile);
		$des_h   = intval($scaled['height'] * $z_tile);
		$src_x   = intval($scaled['x1'] * $z_tile);
		$src_y   = intval($scaled['y1'] * $z_tile);
		$z_ratio = $des_w / $des_h;

		//copy like crop it
		$cp_image = imagecreatetruecolor($des_w, $des_h);
		imagecopy($cp_image, $im, 0, 0, $src_x, $src_y, $des_w, $des_h);

		//write file
		header('Content-Type: '.$a_func['return_type']);
		$a_func['image_render']($cp_image, $new_thumb_path, $a_func['quad']);

		//copy resize
		$thumb_w = $new_dim['thumb_width'];
		$thumb_h = intval($new_dim['thumb_width'] / $z_ratio);
		$thumb   = imagecreatetruecolor($thumb_w, $thumb_h);
		$source  = $a_func['imagecreate']($new_thumb_path);

		// Resize
		imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thumb_w, $thumb_h, $des_w, $des_h);

		// Output
		$a_func['image_render']($thumb, $new_thumb_path, $a_func['quad']);

		// Destroy
		imagedestroy($im);
	}

	public function move_upload($user_path, $temp, $des, $image, $des_need_user_path=null){
		$des_path = "";
		$des_thumb = "";
		$thumb = thumb_name($image);
		$temp_path = $user_path.$temp.$image;
		$temp_thumb = $user_path.$temp.$thumb;

		if($des_need_user_path==null){
			$des_path = $user_path.$des.$image;
			$des_thumb = $user_path.$des.$thumb;
		} else {
			$des_path = $des_need_user_path.$des.$image;
			$des_thumb = $des_need_user_path.$des.$thumb;
		}
		copy($temp_path, $des_path);
		copy($temp_thumb, $des_thumb);
		unlink($temp_path);
		unlink($temp_thumb);
	}
}

?>